import React, { FC, memo, useState, useCallback, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  List,
  ImagePicker,
  InputItem,
  Button,
  NavBar,
  Icon,
  Toast,
} from 'antd-mobile';
import { createForm, FormValidateRule } from 'rc-form';
import { history } from 'umi';
import { loadEditUser } from '@/stores/reducer/user';
import { IRcFormProps, RootState } from '@/interface';

interface IFormValProps {
  phone: number | string;
  sign: string;
}

const UserEdit: FC<IRcFormProps> = props => {
  const [btnLoading, setBtnLoading] = useState(false);
  const dispatch = useDispatch();
  const { getFieldProps, validateFields, getFieldError } = props.form;
  const { avatar, phone, sign } = useSelector((state: RootState) => state.user);
  const [files, setFiles] = useState<any[]>([]);

  useEffect(() => {
    if (avatar) {
      setFiles(() => [{ url: avatar }]);
    }
  }, [avatar]);

  const handleBack = () => {
    history.push('/user');
  };

  const handleImageChage = (files: any[]) => {
    if (files[0]?.file?.size / 1024 / 1024 > 0.1) {
      Toast.fail('图片不能大于0.5M');
      return;
    }
    setFiles(files);
  };

  const handleSubmit = useCallback(() => {
    if (!files || files.length === 0) {
      Toast.info('请上传图片');
      return;
    }
    validateFields(async (error, val: IFormValProps) => {
      if (!error) {
        setBtnLoading(true);
        await dispatch(
          loadEditUser({
            avatar: files[0]?.url,
            phone: val.phone.toString().replace(/\s+/g, ''),
            sign: val.sign,
          }),
        );
        setBtnLoading(false);
      }
    });
  }, [files, setBtnLoading]);

  const errorTips = useCallback((type: string) => {
    Toast.info(getFieldError(type).join('、'));
  }, []);

  const validatePhone = (
    rule: FormValidateRule,
    value: any,
    callback: (error?: any) => void,
  ) => {
    const reg = new RegExp(
      '^1(3([0-35-9]\\d|4[1-8])|4[14-9]\\d|5([0-35689]\\d|7[1-79])|66\\d|7[2-35-8]\\d|8\\d{2}|9[13589]\\d)\\d{7}$',
    );
    const val = value.replace(/\s+/g, '');
    if (reg.test(val)) {
      callback();
    } else if (value.length === 0) {
      callback(new Error('电话不能为空'));
    } else {
      callback(new Error('电话不合法'));
    }
  };

  return (
    <div className="user-edit">
      <NavBar
        mode="light"
        icon={<Icon type="left" />}
        onLeftClick={handleBack}
      />
      <List>
        <List.Item>
          <ImagePicker
            files={files}
            selectable={files.length < 1}
            onChange={handleImageChage}
          />
        </List.Item>
        <InputItem
          {...getFieldProps('phone', {
            rules: [
              { required: true, message: '电话不能为空' },
              { validator: validatePhone },
            ],
            initialValue: phone,
          })}
          clear
          error={!!getFieldError('phone')}
          type="phone"
          onErrorClick={() => errorTips('phone')}
          placeholder="电话"
        >
          电话：
        </InputItem>
        <InputItem
          {...getFieldProps('sign', {
            rules: [{ message: '签名不能为空' }],
            initialValue: sign,
          })}
          clear
          error={!!getFieldError('sign')}
          placeholder="签名"
          onErrorClick={() => errorTips('sign')}
        >
          签名：
        </InputItem>
        <List.Item>
          <Button type="warning" onClick={handleSubmit} loading={btnLoading}>
            修改
          </Button>
        </List.Item>
      </List>
    </div>
  );
};

export default createForm<IRcFormProps>()(memo(UserEdit));
